#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
int main(int argc, char *argv[])
{
  int fpin, fpout;
  off_t res;
  off_t filesize;
  int interpolation_val;
  char current_byte = 0;
  int i,j;

  if(argc < 4)
  {
    printf("please use %s interpolation_val inputfile.gray outputfile.gray\n", argv[0]);
    return 1;
  }
  interpolation_val  = atoi(argv[1]);

  fpin = open(argv[2], O_RDONLY);
  if(fpin < 0)
  {
    printf("input file %s could not be opened\n", argv[2]);
    return 2;
  }
  fpout = open(argv[3], O_CREAT|O_RDWR|O_TRUNC,S_IRUSR|S_IWUSR);
  if(fpout < 0)
  {
    printf("output file %s could not be opened\n", argv[3]);
    return 2;
  }
  filesize = lseek(fpin, 0L, SEEK_END);
  if(filesize < 0)
  {
    perror("fseek1");
    return 3;
  }
  res = lseek(fpin, (off_t)0, SEEK_SET);
  if(res < 0)
  {
    perror("fseek2");
    return 4;
  }

  printf("inputfile has %0ld bytes, interpolation_val %0d\n", filesize, interpolation_val);
  for(i=0;i<filesize;i++)
  {
    if(read(fpin, &current_byte, 1)<0)
    {
      perror("read");
      return 5;
    }
    for(j=0;j<interpolation_val;j++)
    {
      if(write(fpout, &current_byte, 1)<0)
      {
        perror("write");
        return 5;
      }
    }
  }
  close(fpin);
  close(fpout);
  return 0;
}
